package com.example.demoes.utils;

import cn.hutool.core.util.IdUtil;
import com.example.demoes.message.MessageContent;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MsgSenderTemplateUtils implements ApplicationContextAware {

    private static RocketMQTemplate rocketMQTemplate;


    /**
     * 通用message发送接口
     * @param messageContent
     * @return
     */
    public static String sendEventMessage(MessageContent messageContent) {
        String key = IdUtil.fastUUID();
        log.info("消息key={}",key);
        Message<MessageContent> message = MessageBuilder.withPayload(messageContent).setHeader("KEYS",key).build();
        rocketMQTemplate.send(messageContent.getTopic().getValue()+":"+messageContent.getMessageType(), message);
        log.info("消息发送成功 topic[{}],key[{}],data[{}]",messageContent.getTopic().getValue(),key,message.getPayload());
        return key;
    }



    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        rocketMQTemplate = applicationContext.getBean(RocketMQTemplate.class);
    }
}
